<?php
/**
 * Author: lf
 * Blog: https://blog.feehi.com
 * Email: job@feehi.com
 * Created at: 2017-03-15 21:16
 */

namespace common\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * User model
 *
 * @property int                 $id 自增用户id
 * @property string              $username 用户名
 * @property string              $auth_key cookie验证auth_key
 * @property string              $password_hash 加密后密码
 * @property string              $password_reset_token 找回密码token
 * @property string              $email 用户邮箱
 * @property string              $avatar 用户头像url
 * @property int                 $status 用户状态,10为正常
 * @property int                 $created_at 创建时间
 * @property int                 $updated_at 最后修改时间
 * @property string              $signature 个性签名
 * @property string              $description 个人简介
 * @property int                 $gender 性别
 * @property string              $real_name 真实姓名
 * @property string              $phone 联系电话
 * @property int                 $age 年龄
 * @property string              $access_token 存取令牌
 * @property string              $wx_openid 微信openid
 * @property string              $wx_avatar 微信头像
 * @property string              $wx_name 微信昵称
 * @property string              $wx_session_key
 *
 * @property int                 $personCer
 * @property int                 $businessCer
 * @property Image               $avatar0
 * @property Job[]               $jobs
 * @property JobRecord[]         $jobRecords
 * @property Order[]             $orders
 * @property UserCertification[] $userCertifications
 * @property UserConsumption[]   $userConsumptions
 */
class User extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    const WOMAN = 0;
    const MAN = 1;
    public $password;

    public $repassword;

    public $old_password;

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'username'     => Yii::t('app', 'Username'),
            'email'        => Yii::t('app', 'Email'),
            'created_at'   => Yii::t('app', 'Created At'),
            'updated_at'   => Yii::t('app', 'Updated At'),
            'real_name'    => "真实姓名",
            'person_cer'   => "个人认证",
            'business_cer' => "商家认证",
            'age'          => "年龄",
            'description'  => "个人简介",
            'gender'       => "性别",
            'phone'        => "电话号码",


        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    /**
     * Finds user by username
     *
     * @param string $username
     *
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     *
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if ( ! static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status'               => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     *
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int)substr($token, strrpos($token, '_') + 1);
        $expire    = Yii::$app->params['user.passwordResetTokenExpire'];

        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     *
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

    public static function getStatuses()
    {
        return [
            self::STATUS_ACTIVE  => Yii::t('app', 'Normal'),
            self::STATUS_DELETED => Yii::t('app', 'Disabled'),
        ];
    }

    public function getVipAssigment()
    {
        return $this->hasMany(VipAssignment::className(), ['user_id' => 'id']);
    }


    public function getAvatar0()
    {
        return $this->hasOne(Image::className(), ['id' => 'avatar']);
    }

    public function getJobs()
    {
        return $this->hasMany(Job::className(), ['uid' => 'id']);
    }

    public function getJobRecords()
    {
        return $this->hasMany(JobRecord::className(), ['uid' => 'id']);
    }

    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['uid' => 'id']);
    }

    public function getUserCertifications()
    {
        return $this->hasMany(UserCertification::className(), ['uid' => 'id']);
    }

    public function getPersonCer()
    {
        if (UserCertification::findOne([
            'uid'    => $this->id,
            'status' => UserCertification::SUCCESS_STATUS,
            'type'   => UserCertification::PERSONAL_TYPE
        ])) {
            return 1;
        } else {
            return 0;
        }
    }

    public function getBusinessCer()
    {
        if (UserCertification::findOne([
            'uid'    => $this->id,
            'status' => UserCertification::SUCCESS_STATUS,
            'type'   => UserCertification::BUSINESS_TYPE
        ])) {
            return 1;
        } else {
            return 0;
        }
    }


    public function getUserConsumptions() //消费记录
    {
        return $this->hasMany(UserConsumption::className(), ['uid' => 'id']);

    }


    public function getRecords()
    {
        return $this->hasMany(JobRecord::className(), ['uid' => 'id']);
    }

    public function getJob()
    {
        return $this->hasMany(Job::className(), ['uid' => 'id']);
    }


    public static function assignVipRight($userId, Goods $good)
    {

        $vip_assigment = VipAssignment::findOne(['item_name' => $good->right0->item_name, 'user_id' => $userId]);
        if ($vip_assigment != null) {
            $vip_assigment->availability_num += $good->availability_num;
            $vip_assigment->expired_time     += $good->availability_period;
        } else {
            $vip_assigment                   = new VipAssignment();
            $vip_assigment->item_name        = $good->right0->item_name;
            $vip_assigment->user_id          = $userId;
            $vip_assigment->availability_num = $good->availability_num;
            $vip_assigment->expired_time     = time() + $good->availability_period;
        }

        return $vip_assigment->save();

    }

    public static function getMissionNoticeUsers()
    {
        $users = User::find()->joinWith('vipAssigment', true, 'RIGHT JOIN')
                     ->where(['item_name' => 'mission_sms_notice'])
                     ->andWhere(['>', 'expired_time', time()])
                     ->andWhere(['>', 'availability_num', 0])
                     ->all();
        return $users;
    }


    /**
     * @return string
     */
    public function getCurrentAvatar()
    {
        return ! empty($this->avatar) ? $this->avatar0->getImageUrl() : $this->wx_avatar;
    }
}
